<?php

namespace App\Http\Admin\Services;

use App\Exceptions\InvalidRequestException;
use App\Http\Admin\Models\Admin;
use App\Http\Admin\Models\Role;
use Illuminate\Support\Facades\DB;

class RoleService extends BaseService
{

    public function __construct(Role $role)
    {
        parent::__construct($role);
    }

    public function list(){
        $result = $this->model->select(['id','name'])->with('permissions')
            ->orderBy('id','desc')->paginate(20);
        return $result;
    }

    public function del($ids = []){
        $result = $this->delModel($ids);
        return $result;
    }

    public function store($attributes = [])
    {
        $new_attributes = array_only($attributes, ['name']);
        //参数校验
        $this->getValidAttributes($attributes);

        DB::beginTransaction();
        try{
            if(!empty($attributes['id'])){
                //修改过程
                $role = $this->model->where('id',$attributes['id'])->first();
                $role->name = $new_attributes['name'];

                $role->save();
            }else{
                //添加过程
                $role = $this->model->create($new_attributes);
            }
            $role->permissions()->sync($attributes['permission_ids']);
            DB::commit();

        }catch (\Exception $e){
            DB::rollBack();
            throw new InvalidRequestException($e->getMessage());
        }




        return $role;
    }

    public function getValidAttributes($new_attributes)
    {
        if (empty($new_attributes['name'])) {
            throw new InvalidRequestException('请填写角色名');
        }

        if (empty($new_attributes['permission_ids'])) {
            throw new InvalidRequestException('请勾选角色权限');
        }

        if(!empty($new_attributes['id'])){
            $exist = $this->model->where('name',$new_attributes['name'])
                ->where('id','!=',$new_attributes['id'])->exists();
            if($exist){
                throw new InvalidRequestException('角色已存在');
            }
        }else{
            $exist = $this->model->where('name',$new_attributes['name'])->exists();
            if($exist){
                throw new InvalidRequestException('角色已存在');
            }
        }

    }

}
